<template>
  <div class="device-data-source-info">
    <TableHeader>
      <template #headerTop>
        <div class="flex">
          <div class="flex-1">
            <Segmented v-model:value="selectedType" :options="typeTabList" />
          </div>
          <Space :size="1" class="mx-4">
            <Tooltip :title="t('tb.dataSourceInfo.add')">
              <Icon icon="ant-design:plus-outlined" :size="20" class="cursor-pointer" @click="handleAdd" />
            </Tooltip>
            <Tooltip title="刷新数据">
              <Icon icon="ant-design:redo-outlined" :size="20" class="cursor-pointer" @click="fetchDataSources" />
            </Tooltip>
            <Tooltip title="搜索">
              <Icon
                icon="ant-design:search-outlined"
                :size="20"
                class="cursor-pointer"
                @click="() => (showSearch = !showSearch)"
              />
            </Tooltip>
            <Tooltip :title="t('tb.dataSourceInfo.actions.batchDelete')">
              <Icon
                icon="ant-design:delete-outlined"
                :size="20"
                :class="[
                  'cursor-pointer',
                  selectedRowKeys.length === 0 ? 'text-gray-300 cursor-not-allowed' : 'text-red-500',
                ]"
                @click="selectedRowKeys.length > 0 && handleBatchDelete()"
              />
            </Tooltip>
            <template #split>
              <Divider type="vertical" />
            </template>
          </Space>
        </div>
      </template>
    </TableHeader>

    <div v-if="showSearch" class="mb-4">
      <Input
        v-model:value="searchKeyword"
        :placeholder="t('tb.dataSourceInfo.searchPlaceholder')"
        allow-clear
        @change="handleSearch"
      >
        <template #prefix>
          <Icon icon="ant-design:search-outlined" />
        </template>
      </Input>
    </div>

    <BasicTable @register="registerTable" :loading="loading" :dataSource="filteredDataSource">
      <template #typeColumn="{ record }">
        <Tag v-if="record.type === 'database'" color="blue">数据库</Tag>
        <Tag v-else-if="record.type === 'api'" color="green">API</Tag>
        <Tag v-else-if="record.type === 'txt'" color="orange">文件</Tag>
        <Tag v-else>{{ record.type }}</Tag>
      </template>
      <template #configColumn="{ record }">
        <span v-if="record.database">{{ record.database }}</span>
        <span v-else>{{ t('tb.dataSourceInfo.emptyConfig') }}</span>
      </template>
      <template #passwordColumn="{ record }">
        <span v-if="record.password">******</span>
        <span v-else>{{ t('tb.dataSourceInfo.emptyConfig') }}</span>
      </template>
    </BasicTable>

    <CreateOrEditDataSourceModal @register="registerModal" @success="handleSuccess" />
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, computed, onMounted, unref } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { Icon } from '/@/components/Icon';
  import { Space, Divider, Tooltip, Segmented, Input, Tag } from 'ant-design-vue';
  import { BasicTable, BasicColumn, useTable, TableHeader } from '/@/components/Table';
  import { useModal } from '/@/components/Modal';
  import { fetchServiceData, deleteDataSources, type ServiceDataSource } from '/@/api/service/dataSource';
  import CreateOrEditDataSourceModal from './CreateOrEditDataSourceModal.vue';

  const props = defineProps<{
    deviceId?: string;
  }>();

  const { t } = useI18n();
  const { createConfirm, showMessage } = useMessage();

  const selectedType = ref<string>('database');
  const loading = ref(false);
  const dataSource = ref<ServiceDataSource[]>([]);
  const showSearch = ref(false);
  const searchKeyword = ref('');
  const selectedRowKeys = ref<string[]>([]);

  const typeTabList = reactive([
    { value: 'database', label: t('tb.dataSourceInfo.tabs.database'), className: 'segment-tab' },
    { value: 'api', label: t('tb.dataSourceInfo.tabs.api'), className: 'segment-tab' },
    { value: 'txt', label: t('tb.dataSourceInfo.tabs.file'), className: 'segment-tab' },
  ]);

  const tableColumns: BasicColumn[] = [
    {
      title: t('tb.dataSourceInfo.columns.id'),
      dataIndex: 'data_source_id',
      width: 180,
      align: 'center',
    },
    {
      title: t('tb.dataSourceInfo.columns.name'),
      dataIndex: 'name',
      width: 150,
      align: 'center',
    },
    {
      title: t('tb.dataSourceInfo.columns.type'),
      dataIndex: 'type',
      width: 120,
      align: 'center',
      slot: 'typeColumn',
    },
    {
      title: t('tb.dataSourceInfo.columns.ip'),
      dataIndex: 'host',
      width: 150,
      align: 'center',
    },
    {
      title: t('tb.dataSourceInfo.columns.port'),
      dataIndex: 'port',
      width: 100,
      align: 'center',
    },
    {
      title: t('tb.dataSourceInfo.columns.username'),
      dataIndex: 'user',
      width: 120,
      align: 'center',
    },
    {
      title: t('tb.dataSourceInfo.columns.password'),
      dataIndex: 'password',
      width: 120,
      align: 'center',
      slot: 'passwordColumn',
    },
    {
      title: t('tb.dataSourceInfo.columns.config'),
      dataIndex: 'database',
      width: 150,
      align: 'center',
      slot: 'configColumn',
    },
    {
      title: t('tb.dataSourceInfo.columns.owner'),
      dataIndex: 'owner',
      width: 120,
      align: 'center',
    },
    {
      title: t('tb.dataSourceInfo.columns.remark'),
      dataIndex: 'remark',
      width: 200,
      align: 'center',
    },
  ];

  const actionColumn: BasicColumn = {
    width: 180,
    actions: (record: Recordable) => [
      {
        label: t('tb.dataSourceInfo.actions.edit'),
        onClick: handleEdit.bind(null, record as ServiceDataSource),
      },
      {
        label: t('tb.dataSourceInfo.actions.remove'),
        color: 'error',
        onClick: handleDelete.bind(null, record as ServiceDataSource),
      },
      {
        label: t('tb.dataSourceInfo.actions.test'),
        onClick: handleTest.bind(null, record as ServiceDataSource),
      },
    ],
  };

  const [registerModal, { openModal }] = useModal();
  const [registerTable] = useTable({
    rowKey: 'data_source_id',
    columns: tableColumns,
    actionColumn: actionColumn,
    showTableSetting: false,
    useSearchForm: false,
    canResize: true,
    scroll: { y: 520 },
    pagination: false, // 取消分页，接口不支持分页
    striped: false, // 禁用斑马纹
    rowSelection: {
      type: 'checkbox',
      onChange: (keys: string[]) => {
        selectedRowKeys.value = keys as string[];
      },
    },
  });

  const filteredDataSource = computed(() => {
    let result = dataSource.value.filter((item) => item.type === selectedType.value);

    if (searchKeyword.value) {
      const keyword = searchKeyword.value.toLowerCase();
      result = result.filter(
        (item) =>
          item.data_source_id?.toLowerCase().includes(keyword) ||
          item.name?.toLowerCase().includes(keyword) ||
          item.remark?.toLowerCase().includes(keyword),
      );
    }

    return result;
  });

  onMounted(() => {
    fetchDataSources();
  });

  async function fetchDataSources() {
    try {
      loading.value = true;
      const response = await fetchServiceData<ServiceDataSource>(props.deviceId || '', 'source');
      if (response && response.data) {
        // 处理后端返回：无数据时返回 {}，有数据时返回 []
        if (Array.isArray(response.data)) {
          dataSource.value = response.data;
        } else if (typeof response.data === 'object' && Object.keys(response.data).length === 0) {
          // 空对象表示无数据
          dataSource.value = [];
        } else {
          dataSource.value = [];
        }
      } else {
        dataSource.value = [];
      }
    } catch (error: any) {
      console.error('获取数据源列表失败:', error);
      showMessage('获取数据源列表失败', 'error');
      dataSource.value = [];
    } finally {
      loading.value = false;
    }
  }

  function handleSearch() {
    // 搜索由 computed 自动处理
  }

  function handleAdd() {
    openModal(true, {
      isUpdate: false,
      type: selectedType.value,
      deviceId: props.deviceId,
    });
  }

  function handleEdit(record: ServiceDataSource) {
    openModal(true, {
      isUpdate: true,
      record,
      deviceId: props.deviceId,
    });
  }

  function handleDelete(record: ServiceDataSource) {
    createConfirm({
      iconType: 'warning',
      title: t('tb.dataSourceInfo.actions.deleteConfirm'),
      content: `数据源: ${record.name}`,
      centered: false,
      okText: t('tb.dataSourceInfo.actions.remove'),
      okButtonProps: {
        type: 'primary',
        danger: true,
      },
      onOk: async () => {
        try {
          await deleteDataSources(props.deviceId || '', record['.name']);
          showMessage(t('tb.dataSourceInfo.actions.deleteSuccess'), 'success');
          await fetchDataSources();
        } catch (error: any) {
          console.error('删除数据源失败:', error);
          showMessage('删除数据源失败', 'error');
        }
      },
    });
  }

  function handleBatchDelete() {
    if (selectedRowKeys.value.length === 0) {
      return;
    }

    // 获取选中的记录
    const selectedRecords = dataSource.value.filter((item) => selectedRowKeys.value.includes(item.data_source_id));

    // 提取 .name 字段并用逗号连接
    const names = selectedRecords.map((r) => r['.name']).join(',');

    createConfirm({
      iconType: 'warning',
      title: t('tb.dataSourceInfo.actions.batchDeleteConfirm'),
      content: `${t('tb.dataSourceInfo.selectedCount')}: ${selectedRowKeys.value.length}`,
      centered: false,
      okText: t('tb.dataSourceInfo.actions.batchDelete'),
      okButtonProps: {
        type: 'primary',
        danger: true,
      },
      onOk: async () => {
        try {
          await deleteDataSources(props.deviceId || '', names);
          showMessage(t('tb.dataSourceInfo.actions.batchDeleteSuccess'), 'success');
          selectedRowKeys.value = [];
          await fetchDataSources();
        } catch (error: any) {
          console.error('批量删除失败:', error);
          showMessage('批量删除失败', 'error');
        }
      },
    });
  }

  function handleTest(record: ServiceDataSource) {
    showMessage(t('tb.dataSourceInfo.actions.featurePending'), 'info');
  }

  function handleSuccess() {
    fetchDataSources();
  }
</script>

<style lang="less" scoped>
  .device-data-source-info {
    :deep(.segment-tab) {
      min-width: 80px;
      text-align: center;
    }
  }
</style>
